<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :class="{'category-detail-wrap': isDetail}"
    class="order-setting-dialog small-common-dialog-size"
    width="450px">
    <div class="main">
      <Title :title="chartTitle" :style="{marginBottom: isDetail ? '7px' : '16px'}" font-size="16px"/>
      <el-form
        ref="configForm"
        :rules="isDetail ? {} : rules"
        :model="queryData"
        :label-width="isDetail ? '80px' : '80px'"
        label-position="right"
        class="setting-form">
        <el-form-item :label="getLabel('分类名称')" prop="name">
          <el-input
            v-if="!isDetail"
            v-model="queryData.name"
            style="font-size: 13px;width:240px;"
            type="text"
            size="small"
            maxlength="20"
            placeholder="最多20个字符"/>
          <ToolTip v-else :content="queryData.name"/>
        </el-form-item>
        <el-form-item v-if="!(isDetail && !queryData.isAll)" :label="getLabel('可见人员')" prop="isAll">
          <el-radio-group v-if="!isDetail" v-model="queryData.isAll">
            <el-radio :label="1"><span style="font-size:13px;">全部</span></el-radio>
            <el-radio :label="0"><span style="font-size:13px;">指定</span></el-radio>
          </el-radio-group>
          <span v-else>{{ queryData.isAll ? '全部' : '指定' }}</span>
        </el-form-item>
        <template v-if="!queryData.isAll">
          <el-form-item :label="getLabel('可见部门')" prop="departmentList">
            <el-cascader
              v-if="!isDetail"
              ref="department-cascader"
              v-model="queryData.departmentList"
              :show-all-levels="false"
              :options="departmentAll"
              :props="{
                multiple: true,
                checkStrictly: true,
                emitPath:false,
                value: 'id',
                label: 'name',
              }"
              filterable
              collapse-tags
              class="department-all"
              size="small"
              placeholder="请选择部门"
              clearable
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
            <ToolTip v-else :content="queryData.departmentNames"/>

          </el-form-item>
          <el-form-item :label="getLabel('可见人员')" prop="userList">
            <selectWithUserLoad
              v-if="!isDetail"
              ref="selectUser"
              v-model="queryData.userList"
              :hide-select-list="queryData.userList || []"
              :value-type="'object'"
              style="width:240px;"
              placeholder="请选择人员"
              key-name="id"
              label-name="userName"
              multiple
              filterable
              collapse-tags
              clearable
            />
            <CheckUserInfo
              v-else-if="queryData.userList && queryData.userList.length"
              :user-list="queryData.userList"
              :multiple="queryData.userList && queryData.userList.length > 1"
              :user-id="queryData.userList && queryData.userList.length === 1?queryData.userList[0].id:null"
              :label="queryData.userList && queryData.userList.length === 1?queryData.userList[0].name:null"
              key-name="id"
              label-name="name"
            />
            <div v-else>--</div>
          </el-form-item>
        </template>
        <el-form-item :label="getLabel('首页')" prop="isFirstPage" class="is-first-page">
          <el-radio-group v-if="!isDetail" v-model="queryData.isFirstPage">
            <el-radio :label="1"><span style="font-size:13px;">是</span></el-radio>
            <el-radio :label="0"><span style="font-size:13px;">否</span></el-radio>
          </el-radio-group>
          <span v-else>{{ queryData.isFirstPage ? '是' : '否' }}</span>
          <tipIcon :content="`当前用户可见图表类型为首页，且位置值最小，<br>更新时间最新的将被设为用户唯一首页`" class="ml5" use-html/>
        </el-form-item>
        <el-form-item :label="getLabel('图片')">
          <div v-if="!isDetail" class="config-attachment-container" style="width: 240px;">
            <upBackground
              ref="uploadImg"
              :import-api="'/admin/charts/upload'"
              :hide-confirm="true"
              :limit-file-size="3"
              :file-list="queryData.attachment && queryData.attachment.length && queryData.attachment[0].url || ''"
              show-delete
              text="图片尺寸：高80*宽190，大小不超过3M"
              hide-clip-up
              btn-text="上传文件"
              class="img-upload"
              accept="image/gif,image/jpeg,image/jpg,image/png"
              @upProgress="upProgress"
              @complateSetData="complateSetData"
              @removeFileList="removeFileList" />
          </div>
          <FileShowList v-else :file-list="queryData.attachment" style="max-width:100%;" is-show-single-file/>
        </el-form-item>
        <el-form-item :label="getLabel('位置')" prop="index">
          <el-input
            v-if="!isDetail"
            v-model="queryData.index"
            style="font-size: 13px;width:240px;"
            type="number"
            oninput="if(value>10000 )value=10000;if(value<0)value=0;if(value)value=Math.floor(value);if(value.toString().indexOf('.')>=0)value=Number(value.toString().replace('.',''))"
            size="small"
            maxlength="5"
            placeholder="请输入数字，越小位置靠前"
            @mousewheel.native.prevent />
          <span v-else>{{ queryData.index || queryData.index === 0 ? queryData.index : '--' }}</span>
        </el-form-item>
        <el-form-item :label="getLabel('状态')" prop="isEnable">
          <el-radio-group v-if="!isDetail" v-model="queryData.isEnable">
            <el-radio :label="1"><span style="font-size:13px;">启用</span></el-radio>
            <el-radio :label="0"><span style="font-size:13px;">禁用</span></el-radio>
          </el-radio-group>
          <span v-else>{{ queryData.isEnable?'启用':'禁用' }}</span>
        </el-form-item>
        <el-form-item v-if="isDetail" :label="getLabel('更新时间')" prop="updateTime">
          <ToolTip :content="format(queryData.updateTime, 'YYYY/MM/DD HH:mm:ss')" />
        </el-form-item>
      </el-form>
      <div v-if="!isDetail" class="btn-container">
        <el-button :loading="btnLoading" type="primary" size="small" @click="handleOk">确定</el-button>
        <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { mapState } from 'vuex';
import { getDepartmentAll } from '@/api/config';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import upBackground from '@/components/DashboardPage/upBackground';
import FileShowList from '@/components/CreateOrder/fileShowList';
import Title from '@/components/Title';
import { format } from '@/filters/date';

const DIALOG_TYPE = {
  ADD: 0,
  EDIT: 1,
  COPY: 2,
  DETAIL: 3
};
export default {
  name: 'CategoryDialog',
  components: { selectWithUserLoad, upBackground, FileShowList, Title },
  data() {
    const validateName = (msg) => {
      return (rule, value, callback) => {
        const name = this.queryData.name;
        if (!name || name === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    const validateType = (msg) => {
      return (rule, value, callback) => {
        const isAll = this.queryData.isAll;
        if (isAll === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      queryData: {
        name: '',
        isAll: 1,
        index: '',
        isEnable: 1,
        userList: [],
        departmentList: [],
        attachment: [],
        isFirstPage: 0
      },
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateName('请输入分类名称') }],
        isAll: [{ required: true, trigger: 'change', validator: validateType('请选择可见人员') }]
      },
      departmentAll: [],
      dialogVisible: false,
      btnLoading: false,
      type: 0
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    chartTitle() {
      const titleOptions = ['添加图表分类', '编辑图表分类', '复制图表分类及内容', '查看图表分类信息'];
      return titleOptions[this.type];
    },
    isDetail() {
      return this.type === DIALOG_TYPE.DETAIL;
    }
  },
  methods: {
    format,
    async openDialog(data = null, type) {
      data && (this.queryData = data);
      if (!this.isDetail) { await this.getDepartmentAll(); }
      this.type = type;
      this.dialogVisible = true;
    },
    async getDepartmentAll() {
      const res = await getDepartmentAll() || {};
      if (res.code === 200) {
        this.departmentAll = res.data;
      }
    },
    handleOk() {
      const paramsObj = JSON.parse(JSON.stringify(this.queryData));
      if (!paramsObj.isAll && (!paramsObj.departmentList || paramsObj.departmentList.length === 0) && (!paramsObj.userList || paramsObj.userList.length === 0)) {
        this.$message.error('请选择部门或人员');
        return;
      }
      if (paramsObj.userList && paramsObj.userList.length) {
        const userListIds = paramsObj.userList.map(i => i.id);
        paramsObj.userList = userListIds;
      }
      if (paramsObj.index) paramsObj.index = Number(paramsObj.index);
      this.$refs.configForm.validate(valid => {
        if (valid) {
          this.$emit('handleOk', { queryData: paramsObj, type: this.type });
        } else {
          return false;
        }
      });
    },
    clearFormValidate() {
      this.$nextTick(() => {
        this.$refs.configForm.clearValidate();
      });
    },
    // 上传文件
    upProgress() {
      this.loading = true;
    },
    complateSetData({ data, fileName }) {
      this.loading = false;
      const item = {
        name: fileName,
        time: new Date().getTime()
      };
      item.url = typeof data === 'string' ? data : data.url;
      this.queryData.attachment = [item];
    },
    removeFileList() {
      this.queryData.attachment = [];
    },
    handleClose() {
      this.queryData = {
        name: '',
        isAll: 1,
        index: '',
        isEnable: 1,
        userList: [],
        departmentList: [],
        attachment: [],
        isFirstPage: 0
      };
      this.type = 0;
      this.clearFormValidate();
      this.dialogVisible = false;
    },
    getLabel(label) {
      return this.isDetail ? `${label}:` : label;
    }
  }
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
.btn-container {
  display: flex;
  justify-content: center;
}
.charts-tab-main {
  display: flex;
  padding-left: 13px;
  align-items: center;
  .main-title {
    font-size: 14px;
    font-weight: 600;
    line-height: 14px;
    color: #141C3D;
    margin-right: 32px;
  }
}
.overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.department-all {
  width: 240px;
  display: flex;
  align-items: center;
  height: 32px;
  &::v-deep {
    .el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
      display: flex;
      justify-content: center;
      align-items: baseline;
    }
    .el-cascader__tags {
      display: flex;
      align-items: center;
    }
  }
}
.is-first-page {
  display: flex;
  align-items: center;
  &::v-deep {
    .el-form-item__content {
      margin-left: 0 !important;
      display: flex;
      align-items: center;
    }
  }
}
.tip-img {
  display: flex;
  align-items: center;
  margin: -2px 0 0 8px;
  width: 14px;
  height: 14px;
}
.img-upload {
  ::v-deep {
    .img-inner {
      width: 240px !important;
    }
  }
}
.chart-dialog {
  ::v-deep {
    .el-dialog__body {
      padding-top: 16px !important;
    }
    .el-checkbox__label {
      padding-left: 4px;
    }
  }
  .enable-status, .disable-status {
    position: relative;
    span {
      margin-left: 8px;
    }
    &::before {
      content: '';
      width: 4px;
      height: 4px;
      position: absolute;
      left: 0;
      top: 10px;
      border-radius: 50%;
    }
  }
  .enable-status {
    &::before {
      background-color: green;
    }
  }
  .disable-status {
    &::before {
      background-color: red;
    }
  }
}
.category-detail-wrap {
  ::v-deep {
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}
</style>
